/********
 * author: sailing
 * date: 2020/5/14
 * *********/
import eventBus from "./eventBus";
import socket from "./socket";
import mediaControl from "./mediaControl";
class webrtc {
  public pc: any = "";
  public offer: any = "";
  public answer: any = "";
  public sendChannel: any = "";
  public receiveChannel: any = "";
  public otheruser: string = "";
  constructor() {
    this.init();
  }

  public init() {
    const self = this;
    const DEFAULT_ICE_SERVER = {
      iceServers: [{ urls: "stun:stun.stunprotocol.org:3478" }, { urls: "stun:stun.l.google.com:19302" }]
    };
    const configuration = {
      iceServers: DEFAULT_ICE_SERVER
    };
    try {
      this.pc = new RTCPeerConnection(DEFAULT_ICE_SERVER);
      mediaControl.init({
        peer: this.pc
      });
      this.pc.onicecandidate = function(event: any) {
        setTimeout(() => {
          console.log("收到 onicecandidate：", event.candidate);
          if (event.candidate) {
            console.log("收到认证信息:", event.candidate);
            socket.sendMsg("message", {
              type: "webrtcmessage",
              data: {
                to: self.otheruser,
                rtcmessage: {
                  data: event.candidate,
                  type: "candidate"
                }
              }
            });
          }
        });
      };

      this.pc.onicecandidateerror = function(event: any) {
        console.log("onicecandidateerror error:", event);
      };
      /*
      this.sendChannel = this.pc.createDataChannel('sendDataChannel', {
        optional: [{
          RtpDataChannels: true,
        }],
      });
      */

      this.sendChannel = this.pc.createDataChannel("sendDataChannel", {
        reliable: false
      });

      this.sendChannel.onopen = function(e: any) {
        console.log("webrtc Open");
      };

      this.sendChannel.onclose = function(e: any) {
        console.log("data channel close ccccccccccccccccccccccccccccccccccccccc");
      };

      this.pc.ondatachannel = function(event: any) {
        self.receiveChannel = event.channel;
        self.receiveChannel.onmessage = function(event: any) {
          console.log("webrtc receive data:", event.data);
          eventBus.$emit("recvRtcMsg", event.data);
        };
        self.receiveChannel.onopen = function(event: any) {
          console.log("webrtc 已经打开");
        };
      };
    } catch (e) {}
    eventBus.$on("webrtcmessage", this.onWebrtcmessage.bind(this));
  }

  public onWebrtcmessage(msg: any) {
    console.log("webrtc message------------------------:", msg);
    this.otheruser = msg.from;
    const type = msg.rtcmessage.type;

    if (type === "offer") {
      this.pc.setRemoteDescription(new RTCSessionDescription(msg.rtcmessage));
      this.doAnswer();
      console.log("收到Offer 的处理");
    } else if (type === "answer") {
      console.log("收到 answer 之后的处理：", msg.rtcmessage);
      this.pc.setRemoteDescription(new RTCSessionDescription(msg.rtcmessage));
    } else if (type === "candidate") {
      this.pc.addIceCandidate(new RTCIceCandidate(msg.rtcmessage.data));
    }
  }

  public handleIceCandidate(e: any) {
    console.log("ehandleIceCandidate :", e);
  }

  public doCall(otheruser: any) {
    const self = this;
    this.otheruser = otheruser;
    this.pc.createOffer(this.setLocalAndSendMessage.bind(this), this.handleCreateOfferError);
    setTimeout(function() {
      console.log("开始data Channel 发送数据:", self.sendChannel.readyState);
      if (self.sendChannel.readyState == "open") self.sendChannel.send("hello world");
    }, 8000);
  }

  public setLocalAndSendMessage(sessionDescription: any) {
    if (sessionDescription.type === "offer") {
      this.offer = sessionDescription;
    } else {
      this.answer = sessionDescription;
    }
    this.pc.setLocalDescription(sessionDescription);
    socket.sendMsg("message", {
      type: "webrtcmessage",
      data: {
        to: this.otheruser,
        rtcmessage: sessionDescription
      }
    });
    console.log("setLocalAndSendMessage 正在发送消息", sessionDescription);
  }

  public handleCreateOfferError() {
    console.log("error 错误1");
  }

  public onCreateSessionDescriptionError() {
    console.log("error 错误");
  }

  public doAnswer() {
    const self = this;
    console.log("发送 answer 到节点.");
    this.pc.createAnswer().then(self.setLocalAndSendMessage.bind(self), self.onCreateSessionDescriptionError.bind(self));
  }
}

export default new webrtc();
